var showAlert = function(message) {
    if (navigator.notification) {
        navigator.notification.alert(message, function(){});
    } else {
        alert(message);
    }
}

/**
 * handles display of errors to user
 * @param {Error} err
 */
var HandleError = function(err) {
    if (err.message) {
        showAlert(err.message);
    } else {
        showAlert(err);
    }
//    window.location = 'index.html';
};

var goBack = function(page,args) {
    return function() {
        $.mobile.changePage(
                agr.Interface.makeQueryURL(page,args),
                {reverse: true}
                );
    }
}

window.addEventListener('load', function () {
    document.addEventListener('deviceready', function () {
        document.addEventListener('backbutton', function() {
            $.mobile.activePage
                .find('div[data-role="header"] a[data-icon="back"]')
                .filter(':visible').click();
        }, false);
    }, false);
}, false);

/**
 * initializes start page
 * @requires no arguments
 * @param {jQuery.Event} evt
 */
$(document).delegate('#ColonyView', 'pagebeforecreate', function(evt){
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		nextPage:"ColonyMenu",
		editPage:"ColonyDetail",
		model:{
            obj: agr.Model.Colony,
            fn: function(o,lp,st) {
                o.list({view: true},
                    function (arr) {
                        lp.load(arr);
                    },HandleError);
            }
        },
		title: "Colonies",
		noBack:true
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Name;
		},
        bubbleText : function(o) {
            return o.MouseCount;
        }
	})
});

$(document).delegate('#ColonyDetail', 'pagebeforecreate', function(evt) {
    'use strict';
    var dp = new agr.DetailPage($(evt.target),'Colony Detail');

    $(document).undelegate('#ColonyDetail','pagebeforeshow');

    $(document).delegate('#ColonyDetail','pagebeforeshow',function(evt, data) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.Colony.get(args.ColonyID, function(C) {
            dp.setControl(
                C,
                goBack('index',args),
                function done(O) {
                    agr.Model.Colony.update(
                        null,
                        C.ID,
                        O,
                        goBack('index',args),
                        HandleError);
                });
        },HandleError);
    });
});

$(document).delegate('#GenotypeList', 'pagebeforecreate', function(evt){
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ColonyMenu",
		nextPage:"GenotypeDetail",
		editPage:"GenotypeDetail",
		model:{obj: agr.Model.Genotype},
		title: "Genotypes"
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Name;
		}
	})
	
});

$(document).delegate('#MouseList', 'pagebeforecreate', function(evt){
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ColonyMenu",
		nextPage:"MouseDetail",
		editPage:"MouseDetail",
		model:{
			obj: agr.Model.Mouse,
			fn : function(obj,lpage,args){
				// delete litterID so we don't goBack to litterlist
                // probably works, not very pretty

                args.LitterID = null;

				agr.Model.Mouse.list(
					{Colony: args.ColonyID},
					//lpage.load,
                    function (m_arr) {
                        lpage.load(m_arr.filter(function(v,i,a) {
                            return !v.Disabled && v.Tag;
                        }));
                    },
					HandleError);
			}},
		title: "Mice",
		noEdit: true,
		noNew: true  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Tag;
		}
	})		
});

$(document).delegate('#BreedingPairSelect', 'pagebeforecreate', function(evt){
	'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"MouseDetail",
		nextPage:"BreedingPairDetail",
		editPage:"BreedingPairDetail",
		model:{
            obj: agr.Model.BreedingPair,
            fn: function(o,lp,st) {
                o.list({Colony: st.ColonyID, view: true},
                    function (arr) {
                        lp.load(arr);
                    },HandleError);
            }
        },
		title: "Breeding Pair Select",
		noEdit: true,
		noNew : false  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return "BreedingPair" + dbObj.ID;
		},
		bubbleText : function(dbObj){
			return dbObj.LitterCount;
		}
	})
})

$(document).delegate('#BreedingPairList', 'pagebeforecreate', function(evt){
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ColonyMenu",
		nextPage:"LitterList",
		editPage:"BreedingPairDetail",
		model:{
            obj: agr.Model.BreedingPair,
            fn: function(o,lp,st) {
                o.list({Colony: st.ColonyID, view: true},
                    function (arr) {
                        lp.load(arr);
                    },HandleError);
            }
        },
		title: "Breeding Pairs",
		noNew: true  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return "BreedingPair" + dbObj.ID;
		},
		bubbleText : function(dbObj){
			return dbObj.LitterCount;
		}
	})
});

/**
 * initializes page
 * @requires ID argument
 * @param {jQuery.Event} evt
 */
$(document).delegate('#ExperimentView', 'pagebeforecreate', function(evt){
    'use strict';	
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ColonyMenu",
		nextPage:"ExperimentGroupView",
		editPage:"ExperimentDetail",
		model:{
            obj: agr.Model.Experiment,
            fn: function(o,lp,st) {
                o.list({Colony: st.ColonyID, view: true},
                    function (arr) {
                        lp.load(arr);
                    },HandleError);
            }
        },
		title: "Experiments"  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Name;
		},
		bubbleText : function(dbObj){
			return dbObj.ExperimentGroupCount;
		},
        asideText : function(dbObj) {
            return 'Priority: '+ '<b>' + (dbObj.Priority || '0') + '</b>';
        }
	})
    
});

$(document).delegate('#ExperimentGroupView', 'pagebeforecreate', function(evt){
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ExperimentView",
		nextPage:"InterventionList",
		editPage:"ExperimentGroupDetail",
		model:{
            obj: agr.Model.ExperimentGroup,
            fn: function(o,lp,st) {
                o.list({Experiment: st.ExperimentID, view: true},
                    function (arr) {
                        lp.load(arr);
                    },HandleError);
            }
        },
		title: "Experiment Groups"  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Name;
		},
		bubbleText : function(dbObj){
			return dbObj.InterventionCount + '/' + dbObj.MouseQuantity;
		}
	})
});


$(document).delegate('#LitterList','pagebeforecreate',function(evt){
	'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ColonyMenu",
		nextPage:"LitterView",
		editPage:"LitterDetail",
		model:{
			obj: agr.Model.Litter,
			fn : function(obj,lpage,args){
				var target = {};
				if(args.BreedingPairID){
					target.BreedingPair = args.BreedingPairID;
				} else {
                   target.Colony = args.ColonyID;
                }
                target.view = true;
				agr.Model.Litter.list(
					target,
					function(arr){
						lpage.load(arr);	
					},
					HandleError
				)
			}},
		title: "Litters"  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.DateOfBirth + ', ' +
            ((dbObj.BreedingPairID)
             ? 'BreedingPair: ' + dbObj.BreedingPairID
             : 'No BreedingPair');
		},
		bubbleText : function(dbObj){
			return dbObj.MouseCount + '/' + dbObj.Size;
        }
	})
})

$(document).delegate('#LitterView','pagebeforecreate',function(evt){
	'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"LitterList",
		nextPage:"MouseDetail",
		editPage:"MouseDetail",
		model:{
			obj: agr.Model.Mouse,
			fn : function(db,listPage,args) {
            db.list(
                {Litter: args.LitterID},
                listPage.load,
                HandleError);
        	}},
		title: "Mice in Litter"  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Tag;
		}
	})   
})


$(document).delegate('#InterventionList', 'pagebeforecreate', function(evt) {
	'use strict';

    var activeText = ['Inactive', 'In progress', 'Done'];

	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"ExperimentGroupView",
		nextPage:"InterventionDetail",
		editPage:"InterventionDetail",
		model:{obj: agr.Model.Intervention},
        title: "Interventions"  			
	});
	listPage.setFormat({
		mainText : function(dbObj){
			return dbObj.Mouse.Tag;
		},
        asideText : function(dbObj) {
            return (activeText[dbObj.Active] || '') + '&nbsp;';
        },
		secondText : function(dbObj){
			return dbObj.StartDate;
		}
	});
});


$(document).delegate('#ColonyMenu', 'pagebeforecreate', function(evt) {
    'use strict';
	var listPage = agr.ListViewPage({
		page:$(evt.target),
		prevPage:"index",
		model:{
			obj: agr.Model.Colony,
			fn : function(_, listPage, args) {
                var args = agr.Interface.getStateFromURL(evt.target.baseURI);

                // clear args except for ColonyID
                args = {ColonyID: args.ColonyID};

                agr.Model.Colony.get({
                    ID: args.ColonyID,
                    view: true
                }, function(col) {
                        listPage.setTitle(col.Name);
                        listPage.addListItem({
        					html: '<h3>Mice</h3><div class="ui-li-count">' +col.MouseCount+ '</div>',
                            uid: 1,
                        	href:agr.Interface.makeQueryURL('MouseList',args)
                        });
                        listPage.addListItem({
                            uid: 2,
        					html: '<h3>Experiments</h3><div class="ui-li-count">' +col.ExperimentCount+ '</div>',
                            href:agr.Interface.makeQueryURL('ExperimentView',args)
                        });
                        listPage.addListItem({
                            uid: 3,
        					html: '<h3>Breeding Pairs</h3><div class="ui-li-count">' +
                            col.BreedingPairCount+ '</div>',
                            href:agr.Interface.makeQueryURL('BreedingPairList',args)
                        });
                        listPage.addListItem({
                            uid: 4,
        					html: '<h3>Litters</h3><div class="ui-li-count">' +
                            col.LitterCount+ '</div>',
                            href:agr.Interface.makeQueryURL('LitterList',args)
                        });
                        listPage.addListItem({
                            uid: 5,
        					html: '<h3>Genotypes</h3><div class="ui-li-count">' +
                            col.GenotypeCount+ '</div>',
                            href:agr.Interface.makeQueryURL('GenotypeList',args)
                        });
                        listPage.addListItem({
                            uid: 6,
                            html: "<h3>Calendar</h3>",
                            href:agr.Interface.makeQueryURL('Calendar',args)
                        });
                        listPage.addListItem({
                            uid: 7,
                            html: "<h3>Reschedule</h3>",
                            action: function() {
                                agr.Model.Colony.reschedule(
                                    args.ColonyID,
                                    function() {
                                        showAlert('Successfully rescheduled.');
                                    },
                                    HandleError);
                            }
                        });
                        listPage.addListItem({
                            uid: 8,
                            html: "<h3>About Lennie</h3>",
                            href: 'About.html'
                        });
                        listPage.showList();
                    },
                    HandleError);
            }},
		title: "Colony Menu",
		noEdit:true,
		noNew:true  			
	});
});



$(document).delegate('#GenotypeDetail', 'pagebeforecreate', function(evt) {
    'use strict';
    var dp = new agr.DetailPage($(evt.target),'Genotype');

    $(document).undelegate('#GenotypeDetail','pagebeforeshow');

    $(document).delegate('#GenotypeDetail','pagebeforeshow',function(evt, data) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.Genotype.get(
            args.GenotypeID,
            function (G) {
                dp.setControl(
                    G,
                    goBack('GenotypeList',args),
                    function done(O) {
                        agr.Model.Genotype.update(
                            args.ColonyID,
                            G.ID,
                            O,
                            goBack('GenotypeList',args),
                            HandleError);
                    });
            },HandleError);
    });
});

$(document).delegate('#InterventionDetail', 'pagebeforecreate', function(evt) {
    'use strict';
    var dp = new agr.DetailPage($(evt.target),'Intervention');

    $(document).undelegate('#InterventionDetail','pagebeforeshow');

    $(document).delegate('#InterventionDetail','pagebeforeshow',function(evt, data) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.Intervention.get(
            args.InterventionID,
            function (I) {
                dp.setControl(
                    I,
                    goBack('InterventionList',args),
                    function done(O) {
                        agr.Model.Intervention.update(
                            args.ExperimentGroupID,
                            I.ID,
                            O,
                            goBack('InterventionList',args),
                            HandleError);
                    });
            },HandleError);
    });
});

$(document).delegate('#BreedingPairDetail', 'pagebeforecreate', function(evt) {
    'use strict';
    var dp = new agr.DetailPage($(evt.target),'BreedingPair');

    $(document).undelegate('#BreedingPairDetail','pagebeforeshow');

    $(document).delegate('#BreedingPairDetail','pagebeforeshow',
        function(evt, data) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.BreedingPair.get(
            args.BreedingPairID,
            function (BP) {
            	var clone;

            	if(BP.ID){
            		clone = {};
            		$.extend(clone , BP);
            		if((args.MaleID && BP.MaleID) ||
                        (args.FemaleID && BP.FemaleID)){
            			//We need a new object
            			clone.ID = null;	
            		}
            		if(args.MaleID){
                        //male over existing empty male & new male case
            			clone.MaleID = args.MaleID;
            		}
            		if(args.FemaleID){ // ditto for female
            			clone.FemaleID = args.FemaleID;
            		}
            	}
            	else{ //completely new breeding pair, just set what we want
            		if(args.MaleID){
            			BP.MaleID = args.MaleID;
            		}
            		if(args.FemaleID){
            			BP.FemaleID = args.FemaleID;
            		}
            	}
            	
                dp.setControl(
                    (clone)? clone:BP ,
                    goBack('BreedingPairList',args),
                    function done(O) {
                        O.MaleID = parseInt(O.MaleID,10);
                        O.FemaleID = parseInt(O.FemaleID,10);
                        agr.Model.BreedingPair.update(
                            args.ColonyID,
                            (clone)? clone.ID:BP.ID,
                            O,
                            function(){
                                $.mobile.changePage(
                                    agr.Interface.makeQueryURL(
                                        'BreedingPairList',
                                        {ColonyID:args.ColonyID}));
                            }, //CHANGE THIS or clear the state
                            HandleError);
                    });
                 if(args.MaleID || args.FemaleID){  
                 	dp.setEdit(true);
                 }
            },HandleError);
    });
});

$(document).delegate('#MouseDetail', 'pagebeforecreate', function(evt) {
    'use strict';
    var dp = new agr.DetailPage($(evt.target),'Mouse Detail');

    $(document).undelegate('#MouseDetail','pagebeforeshow');

    $(document).delegate('#MouseDetail','pagebeforeshow',function(evt) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        var back_fn = goBack(
            ((args.LitterID)
             ? 'LitterList'
             : 'MouseList'),
            args);

        agr.Model.Mouse.get(
            args.MouseID,
            function(M) {
                agr.Model.Genotype.list(
                    {Colony: args.ColonyID},
                    function(GTs) {
                        dp.setGenotypes(GTs);
                        dp.setControl(
                            M,
                            back_fn,
                            function done(O) {
                                agr.Model.Mouse.update(
                                    args.LitterID,
                                    M.ID,
                                    O,
                                    back_fn,
                                    HandleError);
                            });
                    },HandleError);
            },HandleError);
    });
});


$(document).delegate('#ExperimentDetail', 'pagebeforecreate', function(evt) {
    var dp = new agr.DetailPage($(evt.target),'Experiment Detail');

    $(document).undelegate('#ExperimentDetail','pagebeforeshow');

    $(document).delegate('#ExperimentDetail','pagebeforeshow',function(evt) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.Experiment.get(
            args.ExperimentID,
            function(E) {
                dp.setControl(
                    E,
                    goBack('ExperimentView',args),
                    function done(O) {
                        agr.Model.Experiment.update(
                            args.ColonyID,
                            E.ID,
                            O,
                            goBack('ExperimentView',args),
                            HandleError);
                    });
            },HandleError);
    });
});

$(document).delegate('#LitterDetail', 'pagebeforecreate',function(evt){
	var dp = new agr.DetailPage($(evt.target),'Litter Detail');
	
	$(document).undelegate('#LitterDetail','pagebeforeshow');
	
	$(document).delegate('#LitterDetail','pagebeforeshow',function(evt){
		var args = agr.Interface.getStateFromURL(evt.target.baseURI);

		agr.Model.Litter.get(args.LitterID, function(litter){
			if(!litter.ID && args.BreedingPairID){
				litter.BreedingPairID = args.BreedingPairID;
			}
			dp.setControl(
				litter,
				goBack('LitterList',args),
				function done(o){
					agr.Model.Litter.update(
						args.ColonyID,
						litter.ID,
						o,
						goBack('LitterList',args),
						HandleError);
				}
			)
		},HandleError)	
	});
})

$(document).delegate('#ExperimentGroupDetail', 'pagebeforecreate', function(evt) {
    var dp = new agr.DetailPage($(evt.target),'Group Detail');

    $(document).undelegate('#ExperimentGroupDetail','pagebeforeshow');

    $(document).delegate('#ExperimentGroupDetail','pagebeforeshow',function(evt) {
        var args = agr.Interface.getStateFromURL(evt.target.baseURI);

        agr.Model.ExperimentGroup.get(
            args.ExperimentGroupID,
            function (EG) {
                agr.Model.Genotype.list(
                    {Colony: args.ColonyID},
                    function (GTs) {
                        dp.setGenotypes(GTs);
                        dp.setControl(
                            EG,
                            goBack('ExperimentGroupView',args),
                            function done(O) {
                                agr.Model.ExperimentGroup.update(
                                    args.ExperimentID,
                                    EG.ID,
                                    O,
                                    goBack('ExperimentGroupView',args),
                                    HandleError);
                            });
                    },HandleError);
            },HandleError);
    });
});

/**
 * initializes page
 * @requires 
 * @param {jQuery.Event} evt
 */
var Calendar_init = function(evt) {
    'use strict';

    var args = agr.Interface.getStateFromURL(evt.target.baseURI);
    var datePrepArray = new Array();
	var experimentGroup; 
	
	//Setting up calendar	
    $('#calendar').fullCalendar(
	{ 
        header: {
            left: '',
			center: 'title',
			right: ''
        },    		
		"default" : "month",
		"weekMode" : 'liquid',
		viewDisplay: function(view) 
		{
			//Gather Interventions
			agr.Model.Intervention.list(
	 			{Colony: args.ColonyID}
	 			,function(interventions)
	 			{					
	 				var i=0;					
					datePrepArray = [];
					$('#calendar').fullCalendar('removeEvents').fullCalendar('removeEventSources');
					for(i=0; i<interventions.length; i++)
	 				{							
						addIntervention(interventions[i]);
	 				}					
					for(i=0; i < datePrepArray.length; i++)
					{						
						addEvent(datePrepArray[i][0]+":"+datePrepArray[i][2],  datePrepArray[i][3], datePrepArray[i][1], datePrepArray[i][4]);								
						$('#calendar').fullCalendar('refresh');
					}
					$('#calendar').fullCalendar('refresh');
					agr.Model.ExperimentGroup.list(
						{Colony: args.ColonyID}
						,function(succ)
						{
							var q, id;
							$("#HideShowEvents").empty();
							
							for (q = 0; q <succ.length; q++)
							{
								id = succ[q].ID;
																
								//Add hide show toggle
								$(".fc-event").each(function()
								{
									if(($(this).hasClass("CalEvtClass"+id)) 
									&& ($("#CalEvt"+id).length == 0))
									{
										$("#HideShowEvents").append('<label for="CalEvt'+id+'">'+succ[q].Name+'</label>').trigger( "create" );
										$("#HideShowEvents").append('<input type="checkbox" id="CalEvt'+id+'" checked />').trigger( "create" );

										$("#CalEvt"+id).click(function(){
											$(".CalEvtClass"+($(this).attr('id')).substring(6)).toggle();
										});
									}
								});									
							}
						}
						,HandleError
					);
	 			}
	 			,HandleError
			 );	
   		 }		 
    });	

	//Add events to calendar
    function addEvent(eventName, eventClass, eventStart, eventColor)
    {
        $("#calendar").fullCalendar( 'renderEvent', 
			{
				title: eventName,
				start: eventStart,				
				backgroundColor : eventColor,
				stick : true,
				borderColor: "#000000",
				className: "CalEvtClass"+eventClass
			}, 
			true
        );		
    }


	//Correctly formatting events for calendar
	function addIntervention(intervention)
	{
		var sDate = new Date(""+intervention.StartDate.substring(0, 4), ""+(intervention.StartDate.substring(5, 7)-1), ""+intervention.StartDate.substring(8, 10));
		var eDate = new Date(""+intervention.EndDate.substring(0, 4), ""+(intervention.EndDate.substring(5, 7)-1), ""+intervention.EndDate.substring(8, 10));
		var i, j, k;

		i=j=k=0;	
		
		for (i=0; i<datePrepArray.length; i++)
		{
			if((datePrepArray[i][0] == "S")
			&&(datePrepArray[i][3] == intervention.ExperimentGroupID)
			&&(datePrepArray[i][1]+"" == sDate+""))
			{				
				datePrepArray[i][2]++;
				k=1;
			}
			if((datePrepArray[i][0] == "C")
			&&(datePrepArray[i][3] == intervention.ExperimentGroupID)
			&&(datePrepArray[i][1]+"" == eDate+""))
			{	
				datePrepArray[i][2]++;
				j=1;
			}
		}
		if (k==0)
		{
			datePrepArray.push(["S", sDate, 1, intervention.ExperimentGroupID, "#0400ff"]);					
		}
		if (j==0)
		{
			datePrepArray.push(["C", eDate, 1, intervention.ExperimentGroupID, "#ff0000"]);
		}
	}
	
		
	//Select Month or Week
	$("#MonthWeekSelect").change(function()
	{
		if ($("#MonthWeekSelect :selected").val() == "Month")
		{
			$("#calendar").fullCalendar( 'changeView', "month" );
		}
		else
		{
			$("#calendar").fullCalendar( 'changeView', "basicWeek" );
		}
	});
	
	//Click actions
	$("#Prev").click(function(){$('#calendar').fullCalendar('prev')});
	$("#Next").click(function(){$('#calendar').fullCalendar('next')});
	$("#GetToday").click(function(){$('#calendar').fullCalendar('today')});
	
    //Doesn't fix problem with calendar not showing up without toggling months, weeks, days
    $("#calendar").find(".fc-view-month").css("position", "relative");	
}

$(document).delegate('#Calendar', 'pagebeforeshow', Calendar_init);

$("#Calendar").live("pageshow", function () {
    $("#calendar").fullCalendar("today");
});

$(document).delegate('#ImportExport', 'pagebeforeshow', function(evt) {

    //var args = agr.Interface.getStateFromURL(evt.target.baseURI);

    var $page = $(evt.target);

    $page.find('.import').hide();

	$page.find("#impexp").change(function()
	{		
        $page.find('.export').toggle();
        $page.find('.import').toggle();
	});

    agr.Model.__dump__(function(dump_arr) {
        $page.find('#exportData').val(dump_arr.join(';'));
    });
	
	$("#exportButton").click(function()
	{
        agr.Model.__dump__(function(dump_arr) {
            var mailtostr = 'mailto:dwg@grth.ca';
            mailtostr += '?subject='+window.encodeURIComponent('Colony Data - '+Date());
            document.location.href=mailtostr;
        },HandleError);
	});
	
	$("#importButton").click(function()
	{
		var data = $("#importData").val();
	});
	
});

$(document).delegate('#MouseDetail #breedingButton', 'click', function (evt) {
    if ($('#MouseDetail #ID').val()) {
        var state = agr.Interface.getStateFromURL(evt.target.baseURI);
        if ($("#MouseDetail #Gender").val() == "M") {
            state.MaleID = $('#MouseDetail #ID').val();
        }
        if ($("#MouseDetail #Gender").val() == "F") {
            state.FemaleID = $('#MouseDetail #ID').val();
        }
        var url = agr.Interface.makeQueryURL('BreedingPairSelect', state);
        $.mobile.changePage(url);
    }
});

$(document).delegate('#MouseDetail #ID', 'change', function (evt) {
    var mouseID = parseInt($('#MouseDetail #ID').val(), 10);
    if (mouseID) {
        var url;
        var state = agr.Interface.getStateFromURL(evt.target.baseURI);
        agr.Model.Intervention.list({
            Mouse: mouseID
        }, function (arr) {
            if (arr[0]) {
                state.InterventionID = arr[0].ID;
                url = agr.Interface.makeQueryURL('InterventionDetail', state);
                $('#interventionButton').click(function () {});
                $('#interventionButton').click(function () {
                    $.mobile.changePage(url)
                });
            } else {
                $('#interventionButton').val("Not In Intervention");
                $('#interventionButton').button('refresh');
            }
        }, HandleError)
    }
});


/*$(document).undelegate('#ID');
$(document).undelegate('#MaleIDButton');
$(document).undelegate('#FemaleIDButton');*/

$(document).delegate('#BreedingPairDetail #ID', 'change', function (evt) {

    if ($('#BreedingPairDetail #ID').val()) {
        //console.log($('#BreedingPairDetail #ID').val());

        $(document).undelegate('#BreedingPairDetail #MaleIDButton');
        $(document).delegate('#BreedingPairDetail #MaleIDButton', 'click', function (evt) {
            var state = agr.Interface.getStateFromURL(evt.target.baseURI);
            $.mobile.changePage(
            agr.Interface.makeQueryURL('MouseList', {
                ColonyID: state.ColonyID,
                Qualify: {
                    field: "Gender",
                    value: "M"
                }
            }));
        });

        $(document).undelegate('#BreedingPairDetail #FemaleIDButton');
        $(document).delegate('#BreedingPairDetail #FemaleIDButton', 'click', function (evt) {
            var state = agr.Interface.getStateFromURL(evt.target.baseURI);
            $.mobile.changePage(
            agr.Interface.makeQueryURL('MouseList', {
                ColonyID: state.ColonyID,
                Qualify: {
                    field: "Gender",
                    value: "F"
                }
            }));
        });
    }

});

$(document).delegate('#BreedingPairDetail #MaleID', 'change', function (evt) {
    if ($('#BreedingPairDetail #MaleID').val()) {
        agr.Model.Mouse.get($('#BreedingPairDetail #MaleID').val(), function (mouse) {
            $('#BreedingPairDetail #MaleIDButton').find('.ui-btn-text').text(mouse.Tag);
            $(document).undelegate('#BreedingPairDetail #MaleIDButton');
            $(document).delegate('#BreedingPairDetail #MaleIDButton', 'click', function (evt) {
                state = agr.Interface.getStateFromURL(evt.target.baseURI);
                if ($('#BreedingPairDetail #MaleID').val()) {
                    $.mobile.changePage(
                    agr.Interface.makeQueryURL('MouseDetail', {
                        ColonyID: state.ColonyID,
                        MouseID: $('#BreedingPairDetail #MaleID').val()
                    }));
                }
            });
        }, HandleError)
    }
});

$(document).delegate('#BreedingPairDetail #FemaleID', 'change', function (evt) {
    if ($('#BreedingPairDetail #FemaleID').val()) {
        agr.Model.Mouse.get($('#BreedingPairDetail #FemaleID').val(), function (mouse) {
            $('#BreedingPairDetail #FemaleIDButton').find('.ui-btn-text').text(mouse.Tag);
            $(document).undelegate('#BreedingPairDetail #FemaleIDButton');
            $(document).delegate('#BreedingPairDetail #FemaleIDButton', 'click', function (evt) {
                state = agr.Interface.getStateFromURL(evt.target.baseURI);
                if ($('#BreedingPairDetail #FemaleID').val()) {
                    $.mobile.changePage(
                    agr.Interface.makeQueryURL('MouseDetail', {
                        ColonyID: state.ColonyID,
                        MouseID: $('#BreedingPairDetail #FemaleID').val()
                    }));
                }
            });
        }, HandleError)
    }
});

$(document).delegate('#InterventionDetail #MouseID', 'change', function (evt) {
    if ($('#InterventionDetail #MouseID').val()) {
        agr.Model.Mouse.get($('#InterventionDetail #MouseID').val(), function (mouse) {
            $('#InterventionDetail #MouseIDButton').find('.ui-btn-text').text(mouse.Tag);

            $(document).undelegate('#InterventionDetail #MouseIDButton');
            $(document).delegate('#InterventionDetail #MouseIDButton', 'click', function (evt) {
                state = agr.Interface.getStateFromURL(evt.target.baseURI);
                $.mobile.changePage(
                agr.Interface.makeQueryURL('MouseDetail', {
                    ColonyID: state.ColonyID,
                    MouseID: mouse.ID
                }));
            });
        }, HandleError)
    }
});
